<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import { ElTree, ElInput, ElDivider, ElTag, ElUpload, ElIcon, ElMessage } from 'element-plus'
import { selectionType } from '@/api/login/types'
import { getUserListApi } from '@/api/department'
import {
  GetScoreCriteriaApi,
  DeleteScoreCriteriaApi,
  AddScoreCriteriaApi,
  EditScoreCriteriaApi,
  GetUndoneCoursesApi,
  DownloadScoreCriteriaTemplateApi
} from '@/api/course'
import * as XLSX from 'xlsx'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/ScoreCriteriaWrite.vue'
import Detail from './components/ScoreCriteriaDetail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { useButtonPermiss } from '@/utils/buttonpermiss'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const headers = ref({ Authorization: userStore.getToken ?? '' })
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()

const { t } = useI18n()
interface scoreCriteria {
  remark: string
  scoreItem: string
  scoreValue: number
  scoreContent: string
  createTime: string
  children?: scoreCriteria[]
}
let list: scoreCriteria[] = []
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await GetScoreCriteriaApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    list = res.data.pageModels || []
    return {
      list: list,
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await DeleteScoreCriteriaApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const chooes = ref<String[]>([])
const selectRef = ref()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'scoreGroup',
    label: '分组',
    sortable: true,
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: '分组',
    form: {
      component: 'Input'
      // componentProps: {
      //   type: 'textarea',
      //   rows: 4,
      //   placeholder: '请输入备注'
      // }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'scoreItem',
    label: '评分分项',
    sortable: true
  },

  {
    field: 'scoreValue',
    label: '分值',
    width: '80px',
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number',
        placeholder: '请输入分值'
      }
    },
    sortable: true
  },
  {
    field: 'scoreContent',
    label: '评分标准',
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 4,
        placeholder: '请输入评分标准'
      }
    },
    sortable: true
  },

  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    width: '170px',
    form: {
      hidden: true
    },
    sortable: true,
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },

  {
    field: 'date',
    label: t('problem.time'),
    search: {
      component: 'DatePicker',
      componentProps: {
        style: { width: '340px' },
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    fixed: 'right',
    width: 320,
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },

    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row
          return row.scoreGroup ? null : (
            <>
              {haspermiss.value.includes('编辑') ? (
                <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                  {t('exampleDemo.edit')}
                </BaseButton>
              ) : null}
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              {haspermiss.value.includes('删除') ? (
                <BaseButton type="danger" onClick={() => delData(data.row)}>
                  {t('exampleDemo.del')}
                </BaseButton>
              ) : null}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
  chooes.value = []
}

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type

  dialogVisible.value = true
  let arr: String[] = []
  if (row.planUsers) {
    JSON.parse(row.planUsers).map((i) => {
      arr.push(i.UserNo + '$' + i.UserName)
    })
    chooes.value = arr
  }
  console.log('------------', arr)
  currentRow.value = { ...row, chooes: arr }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

// const filterDep = (value: string, data: DepartmentItem) => {}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      console.log('formData---', formData)

      let res
      if (actionType.value == 'edit') {
        formData.guid = currentRow.value.guid
        res = await EditScoreCriteriaApi(formData).finally(() => {
          saveLoading.value = false
        })
      } else {
        res = await AddScoreCriteriaApi(formData).finally(() => {
          saveLoading.value = false
        })
      }
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const showExport = ref(false)
interface coursExport {
  分组: string
  评分项: string
  分值: number
  评分标准: string
  创建时间: string
}
const handleData = () => {
  let arr: coursExport[] = []
  list.map((p) => {
    p.children?.map((item) => {
      arr.push({
        分组: item.remark,
        评分项: item.scoreItem,
        分值: item.scoreValue,
        评分标准: item.scoreContent,
        创建时间: item.createTime
      })
    })
  })
  return arr
}
const exportToExcel = () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '评分规则列表.xlsx')
}
const successFile = (e) => {
  console.log('successFile-------', e)
  if (e.code == 0) {
    ElMessage.success('导入成功')
    showExport.value = false
    getList()
  } else {
    ElMessage.error(e.msg || '导入失败')
  }
}
const downExcel = async () => {
  const res = await DownloadScoreCriteriaTemplateApi()
  if (res) {
    const excelFile = new Blob([res.data], {
      type: 'application/vnd.ms-excel'
    })

    // const url = URL.createObjectURL(excelFile)
    const url = window.URL.createObjectURL(excelFile)
    const a: HTMLAnchorElement = document.createElement('a')
    // 设置<a>元素的属性
    a.href = url
    a.download = '评分规则模板.xlsx'
    // 将<a>元素添加到文档中
    document.body.appendChild(a)
    // 触发点击事件
    a.click()
    URL.revokeObjectURL(a.href)
    // 移除<a>元素
    document.body.removeChild(a)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
        t('exampleDemo.add')
      }}</BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        @click="delData(null)"
        v-if="haspermiss.includes('删除')"
      >
        {{ t('exampleDemo.del') }}
      </BaseButton>
      <BaseButton type="primary" @click="showExport = true" v-if="haspermiss.includes('导入')">{{
        t('exampleDemo.import')
      }}</BaseButton>
      <BaseButton type="primary" @click="exportToExcel" v-if="haspermiss.includes('导出')">{{
        t('exampleDemo.exprot')
      }}</BaseButton>
      <BaseButton type="primary" @click="downExcel">下载模板</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
      rowKey="guid"
      :defaultExpandAll="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" :max-height="600">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
      :chooes="chooes"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="showExport" title="导入模板">
    <div class="uploaddiv">
      <ElUpload
        accept=".xlsx, .xls"
        drag
        action="/api/ScoreCriteria/ExportScoreCriteria"
        :headers="headers"
        :on-success="successFile"
      >
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        <div class="el-upload__text">点击或拖拽文件到此处上传</div>
        <div class="el-upload__text">支持.xlsx, .xls</div>
      </ElUpload>
    </div>
    <template #footer>
      <BaseButton @click="showExport = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
